package com.whf.android.jar.base.latte;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.base.delegate.IPageLoadListener;
import com.whf.android.jar.net.HttpCode;
import com.whf.android.jar.net.callback.IError;
import com.whf.android.jar.net.callback.IFailure;
import com.whf.android.jar.net.callback.ISuccess;
import com.whf.android.jar.net.utils.RestClientUtils;
import com.whf.android.jar.popup.listener.OnClickDecisionListener;
import com.whf.android.jar.util.activity.AndroidBug5497Workaround;
import com.whf.android.jar.util.battery.BatteryOptimizedPopup;

import java.util.List;
import java.util.WeakHashMap;

/**
 * 基础界面
 *
 * @author qf
 * @version 2020-03-23
 */
abstract class AbstractActivity extends AppCompatActivity implements IPageLoadListener,
        IFailure, IError, ISuActivity {

    protected final static String STATE_OUT = "outSign";
    private LoadingPopupView loadingPopup = null;

    // 字体大小不跟随系统
    @Override
    protected void attachBaseContext(Context newBase) {
        if (newBase != null) {
            Configuration configuration = newBase.getResources().getConfiguration();
            configuration.fontScale = Latte.fontScale();
            super.attachBaseContext(newBase.createConfigurationContext(configuration));
        }
    }

    /**
     * 确定应用程序是否已经忽略电池优化
     */
    @SuppressLint("BatteryLife")
    private boolean isIgnoringBatteryOptimizations() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return false;
        }
        if (!isBattery()) {
            return false;
        }
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = !powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }

        Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        Intent intent2 = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
        intent2.setData(Uri.parse("package:" + getPackageName()));

        boolean isIntent = intent.resolveActivity(getPackageManager()) != null
                || intent2.resolveActivity(getPackageManager()) != null;

        return isIgnoring && isIntent;
    }

    /**
     * 应用程序是否需要忽略电池优化
     */
    protected boolean isBattery() {
        return true;
    }

    /**
     * 应用程序忽略电池优化
     */
    protected void initBattery() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M && isIgnoringBatteryOptimizations()) {
            BatteryOptimizedPopup.create(this).setOnClickListener(new OnClickDecisionListener() {
                @Override
                public void onConfirm(Object decision) {
                    @SuppressLint("BatteryLife")
                    Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    //跳转之前判断intent是否存在，否则有的机型会报找不到activity
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        startActivity(intent);
                    } else {
                        intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivity(intent);
                        } else {
                            ToastUtils.showShort("无法关闭电池优化，请手动关闭！");
                        }
                    }
                }

                @Override
                public void onCancel() {

                }
            }).popup();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //持有当前activity
        Latte.getConfigurator().withActivity(this);
        try {
            AndroidBug5497Workaround.assistActivity(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //返回时，拿到当前activity
        Latte.getConfigurator().withActivity(this);
    }

    @Override
    public void showLoading() {
        showLoading("正在加载中");
    }

    @Override
    public void showLoading(String loading) {
        showLoading(loading, false);
    }

    @Override
    public void showLoading(String loading, boolean showLoading) {
        if (loadingPopup == null) {
            loadingPopup = (LoadingPopupView) new XPopup.Builder(this)
                    .dismissOnTouchOutside(showLoading)
                    .dismissOnBackPressed(showLoading)
                    .asLoading(loading)
                    .show();
        } else {
            loadingPopup.setTitle(loading).show();
        }
    }

    @Override
    public void hideLoading() {
        if (null != loadingPopup) {
            loadingPopup.dismiss();
        }
    }

    @Override
    public void inGet(String url, ISuccess success) {
        RestClientUtils.create(this, this)
                .inGet(url, success);
    }

    @Override
    public void inGet(String url, String ids, ISuccess success) {
        RestClientUtils.create(this, this)
                .inGet(url, ids, success);
    }

    @Override
    public void inGet(String url, WeakHashMap<String, Object> params, ISuccess success) {
        RestClientUtils.create(this, this)
                .inGet(url, params, success);
    }

    @Override
    public void inPost(String url, WeakHashMap<String, Object> params, ISuccess success) {
        RestClientUtils.create(this, this)
                .inPost(url, params, success);
    }

    @Override
    public void inPost(String url, String data, ISuccess success) {
        RestClientUtils.create(this, this)
                .inPost(url, data, success);
    }

    @Override
    public void inPost(String url, ISuccess success) {
        RestClientUtils.create(this, this)
                .inPost(url, success);
    }

    @Override
    public void inPut(String url, String data, ISuccess success) {
        RestClientUtils.create(this, this)
                .inPut(url, data, success);
    }

    @Override
    public void inPath(String url, List<String> result, ISuccess success) {
        RestClientUtils.create(this, this)
                .inPath(url, result, success);
    }


    @Override
    public void inPath(String url, String data, ISuccess success) {
        RestClientUtils.create(this, this)
                .inPath(url, data, success);
    }

    @Override
    public void download(String url, String name, ISuccess success) {
        RestClientUtils.create(this, this)
                .download(url, name, success);
    }


    @Override
    public void onFailure() {
        hideLoading();
        ToastUtils.showShort("连接服务器失败，请稍后再试。");
    }

    @Override
    public void onError(int code, String msg) {
        hideLoading();
        if (Latte.getSignExpiration() == code) {
            ToastUtils.showShort("登录超时");
            outSignIn();
        } else if (HttpCode.CODE_404 == code) {
            ToastUtils.showShort("服务器找不到请求的接口");
        } else if (HttpCode.CODE_500 == code && Latte.getServerError()) {
            ToastUtils.showShort("服务器遇到错误，无法完成请求");
        } else if (HttpCode.CODE_501 == code && Latte.getServerError()) {
            ToastUtils.showShort("服务器无法识别请求方法");
        } else if (HttpCode.CODE_502 == code && Latte.getServerError()) {
            ToastUtils.showShort("服务器网关或代理错误，无法完成请求");
        } else if (HttpCode.CODE_503 == code && Latte.getServerError()) {
            ToastUtils.showShort("服务器目前无法使用");
        } else if (HttpCode.CODE_504 == code && Latte.getServerError()) {
            ToastUtils.showShort("服务器网关或代理超时，无法完成请求");
        } else if (HttpCode.CODE_505 == code && Latte.getServerError()) {
            ToastUtils.showShort("服务器不支持请求中所用的 HTTP 协议版本");
        } else if (ObjectUtils.isEmpty(msg)) {
            ToastUtils.showShort("服务器异常，请联系管理员");
        } else {
            ToastUtils.showShort(msg);
        }
    }

    @Override
    public Class<? extends Activity> outSignInActivity() {
        return null;
    }
}
